<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	function __construct(){
		parent::__construct();
		$this->load->model('user_model','user_model');
		$this->load->model('admin/banner_model','banner_model');
		$this->lang->load('main', 'thai');
	}
	
	public function index()
	{
		redirect('/user/login');
	}
	
	function dashboard()
	{
		if($this->session->userdata('logged_in') == FALSE){
			redirect('/user/login');
		}else{
			$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('dashboard');
			$this->template->set_template('page');
			$this->template->write_view('header','home/master/header',$header , false);
			
			//$banner = $this->banner_model->get_banner();
			
			$data['block_title'] = $this->lang->line('dashboard');
			$banner['user_block'] = get_user_box();
			$data['message'] = $this->lang->line('dashboard');
			$data['user_info'] = $this->user_model->getUserInfo($this->session->userdata('username'));
			$data['company_info'] = $this->user_model->getCompanyInfo($this->session->userdata('user_id'));
			
			if($data['user_info']['role_id'] == 1){
				$data['user_info']['level'] = $this->lang->line('general_level');
			}else{
				if($data['user_info']['gold_active'] != 1){
					$data['user_info']['level'] = $this->lang->line('general_level');
				}else{
					if($data['user_info']['gold_start'] <= time() AND $data['user_info']['gold_finish'] >= time()){
						$data['user_info']['level'] = $this->lang->line('gold_level').' <label id="gold_expire" class="red">(expire on '.date('d/m/Y',$data['user_info']['gold_finish']).')</label>';
					}else{
						$data['user_info']['level'] = $this->lang->line('general_level');
					}
				}
			}
			
			$this->load->model('admin/category_model','category_model');
			$main_cat_id = $this->category_model->getCatParrentId($data['company_info']['cat_id']);
			$category_option = $this->category_model->lists(0,1,500);
			$data['category_option'] = array();
			$i = 0;
			foreach($category_option as $v){
				$data['category_option'][$i]['id'] = $v->id;
				$data['category_option'][$i]['name_th'] = $v->name_th;
				$data['category_option'][$i]['selected'] = '';
				if($v->id==$main_cat_id){
					$data['category_option'][$i]['selected'] = 'selected="selected"';
				}
				$i++;
			}
			
			$sub_category_option = $this->category_model->lists($main_cat_id,1,500);
			$data['sub_category_option'] = array();
			$i = 0;
			foreach($sub_category_option as $v){
				$data['sub_category_option'][$i]['id'] = $v->id;
				$data['sub_category_option'][$i]['name_th'] = $v->name_th;
				$data['sub_category_option'][$i]['selected'] = '';
				if($v->id==$data['company_info']['cat_id']){
					$data['sub_category_option'][$i]['selected'] = 'selected="selected"';
				}
				$i++;
			}
			
			$this->load->model('admin/province_model','province_model');
			$province_option = $this->province_model->lists();
			$data['province_option'] = array();
			$i = 0;
			foreach($province_option as $v){
				$data['province_option'][$i]['PROVINCE_ID'] = $v->PROVINCE_ID;
				$data['province_option'][$i]['PROVINCE_NAME'] = $v->PROVINCE_NAME;
				$data['province_option'][$i]['selected'] = '';
				if($v->PROVINCE_ID==$data['company_info']['province']){
					$data['province_option'][$i]['selected'] = 'selected="selected"';
				}
				$i++;
			}
			
			$website_info = $this->user_model->getCompanyWebsiteByCompanyId($data['company_info']['id']);
			if(count($website_info) > 0){
				$website_info['created'] = TRUE;
				
			}else{
				$website_info['created'] = FALSE;
			}
			
			$data['website_info'] = $website_info;
			
			$this->template->write_view('sideleft','home/master/sidebar_left',$banner);
			$this->template->write_view('sideright','home/master/sidebar_right',$banner);
			
			$this->template->write_view('search_form','home/master/page_search');
			$this->template->write_view('content', 'dashboard',$data);
			$this->template->write_view('footer','home/master/footer');
			$this->template->render();
		}
	}
	
	function login()
	{
		if($this->session->userdata('logged_in') == FALSE){
			$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('login');
			$data['block_title'] = $this->lang->line('login');
			
			$this->template->set_template('page');
			$this->template->write_view('header','home/master/header',$header , false);
			
			//$banner = $this->banner_model->get_banner();
			$banner['user_block'] = get_user_box();
			$this->template->write_view('sideleft','home/master/sidebar_left',$banner);
			$this->template->write_view('sideright','home/master/sidebar_right',$banner);
			
			$this->template->write_view('search_form','home/master/page_search');
			$this->template->write_view('content', 'register' ,$data);
			$this->template->write_view('footer','home/master/footer');
			$this->template->render();
		}else{
			redirect('/user/dashboard');
		}
	}
	
	function logout()
	{
		$this->session->sess_destroy();
		redirect(site_url());
	}
	
	function setting()
	{
		echo 'setting';
	}
	
	function register()
	{
		if($this->session->userdata('logged_in') == FALSE){
			//$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('register');
			//$data['block_title'] = $this->lang->line('register');
			//
			//$this->template->set_template('page');
			//$this->template->write_view('header','home/master/header',$header , false);
			//
			////$banner = $this->banner_model->get_banner();
			//$banner['user_block'] = get_user_box();
			//$this->template->write_view('sideleft','home/master/sidebar_left',$banner);
			//$this->template->write_view('sideright','home/master/sidebar_right',$banner);
			//
			//$this->template->write_view('search_form','home/master/page_search');
			//$this->template->write_view('content', 'register' ,$data);
			//$this->template->write_view('footer','home/master/footer');
			//$this->template->render();
			$this->register_step2();
		}else{
			redirect('/user/dashboard');
		}
	}
	
	function register_step2()
	{
		//if(!isset($_POST['email']) OR $_POST['email']==''){
		//	$this->register();
		//}else{
			$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('register');
			//$data['email'] = $_POST['email'];
			$data['email'] = '';
			$this->template->set_template('page');
			$this->template->write_view('header','home/master/header',$header , false);
			
			//$banner = $this->banner_model->get_banner();
			$banner['user_block'] = get_user_box();
			$this->template->write_view('sideleft','home/master/sidebar_left',$banner);
			$this->template->write_view('sideright','home/master/sidebar_right',$banner);
			
			$this->template->write_view('search_form','home/master/page_search');
			
			$this->load->model('admin/category_model','category_model');
			$data['category_option'] = $this->category_model->lists(0,1,500);
			
			$this->load->model('admin/province_model','province_model');
			$data['province_option'] = $this->province_model->lists();
			$data['block_title'] = $this->lang->line('register');
			//if($_POST['group']==1){
			//	$this->template->write_view('content', 'register_step2_member' , $data);
			//}else{
				$this->template->write_view('content', 'register_step2_supplier' , $data);
			//}
			
			$this->template->write_view('footer','home/master/footer');
			$this->template->render();
		//}
	}
	
	function register_step3()
	{
		if(!isset($_POST['email']) OR $_POST['email']==''){
			$this->register();
		}else{
			$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('register');
			$time = time();
			
			$member['role_id'] = $_POST['group'];
			$member['regis'] = $_POST['member_gold'];
			$member['email'] = $_POST['email'];
			$member['firstname'] = $_POST['firstname'];
			$member['lastname'] = $_POST['lastname'];
			$member['username'] = $_POST['username'];
			$member['password'] = md5($_POST['password']);
			$member['tel'] = $_POST['member_tel'];
			$member['created'] = $time;
			$member['seckey'] = md5($time.rand(-100,100));
			$id = $this->user_model->add_supplier($member);
			
			if($id>0){
				if($_POST['group']==2){
					$this->load->model('admin/province_model','province_model');
					$company['user_id'] = $id;
					$company['name'] = $_POST['company_name'];
					$company['main_cat_id'] = $_POST['company_category'];
					$company['cat_id'] = $_POST['company_subcat'];
					$company['address'] = $_POST['company_address'];
					$company['district'] = $_POST['company_district'];
					$company['geo_id'] = $this->province_model->get_geo_id($_POST['company_province']);
					$company['province'] = $_POST['company_province'];
					$company['postcode'] = $_POST['company_postcode'];
					$company['country'] = $_POST['company_country'];
					$company['agent'] = $_POST['company_agent'];
					$company['website'] = $_POST['company_website'];
					$company['email'] = $_POST['company_email'];
					$company['tel'] = $_POST['company_tel'];
					$company['fax'] = $_POST['company_fax'];
					$company['brand'] = $_POST['company_brand'];
					$company_id = $this->user_model->add_company($company);
					if($company_id>0){
						$this->load->library('ciupload');
						$img_msg = '';
						$logo_msg = '';
						if(isset($_FILES["img"]) && is_uploaded_file($_FILES["img"]["tmp_name"]) && $_FILES["img"]["tmp_name"]!=''){
							$this->ciupload->Upload($_FILES['img']);
							if ($this->ciupload->uploaded){
								$this->ciupload->image_resize = true;
								$this->ciupload->image_ratio_fill = true;
								$this->ciupload->image_x = 156;
								$this->ciupload->image_y = 100;
								$this->ciupload->Process(APPPATH.'../assets/image/company/'.$company_id);
								
								if ($this->ciupload->processed){
									$input['user_id'] = $id;
									$input['id'] = $company_id;
									$input['img'] = $this->ciupload->file_dst_name;
									$result = $this->user_model->update_company_img($input);
									if($result==0){
										@unlink(APPPATH.'../assets/image/company/'.$company_id.'/'.$this->ciupload->file_dst_name);
										$img_msg = $this->lang->line('image_not_upload');
									}
								}else{
									$img_msg = $this->lang->line('image_not_upload');
								}
							}else{
								$img_msg = $this->lang->line('image_not_upload');
							}
						}
						
						if(isset($_FILES["logoimg"]) && is_uploaded_file($_FILES["logoimg"]["tmp_name"]) && $_FILES["logoimg"]["tmp_name"]!=''){
							$this->ciupload->Upload($_FILES['logoimg']);
							if ($this->ciupload->uploaded){
								$this->ciupload->image_resize = true;
								$this->ciupload->image_ratio_fill = true;
								$this->ciupload->image_x = 35;
								$this->ciupload->image_y = 35;
								$this->ciupload->Process(APPPATH.'../assets/image/company/'.$company_id);
								
								if ($this->ciupload->processed){
									$input['user_id'] = $id;
									$input['id'] = $company_id;
									$input['logo'] = $this->ciupload->file_dst_name;
									$result = $this->user_model->update_company_logo($input);
									if($result==0){
										@unlink(APPPATH.'../assets/image/company/'.$company_id.'/'.$this->ciupload->file_dst_name);
										$logo_msg = $this->lang->line('image_not_upload');
									}
								}else{
									$logo_msg = $this->lang->line('image_not_upload');
								}
							}else{
								$logo_msg = $this->lang->line('image_not_upload');
							}
						}
						
						$this->load->library('cimailer','cimailer');
						$file = APPPATH.'../assets/mail/user_regis.txt';
						$handle = fopen($file,'r');
						$body = '';
						if ($handle) {
							while (!feof($handle)) {
								$file_ = fgets($handle, 4096);
								$body .= $file_."<br>";
							}
							fclose($handle);
						}
						
						try {
							//$this->cimailer->IsMail();
							$this->cimailer->CharSet="utf-8";
							$this->cimailer->IsHTML(true);
							$this->cimailer->From = $this->config->item('main_email');
							
							$body = str_replace('{NAME}',$_POST['firstname'],$body);
							$body = str_replace('{LASTNAME}',$_POST['lastname'],$body);
							$body = str_replace('{USERNAME}',$member['username'],$body);
							$body = str_replace('{SITENAME}',$this->config->item('site_name'),$body);
							$body = str_replace('{SECCODE}',$member['seckey'],$body);
							$body = str_replace('{PASSWORD}',$_POST['password'],$body);
							$body = str_replace('{CONFIRMLINK}',base_url()."user/register/confirm/{$member['seckey']}",$body);
							
							$this->cimailer->FromName = $this->config->item('register_conf_title');
							$this->cimailer->AddReplyTo($this->config->item('main_email'), $this->config->item('register_conf_title'));
							$this->cimailer->AddAddress($member['email']);
							$this->cimailer->Subject = $this->config->item('register_conf_title');
							$this->cimailer->Body = $body;
							
							if($this->cimailer->Send()){
								$data['message'] = $this->lang->line('regis_complete');
							}else{
								$data['message'] = $this->lang->line('mail_not_send');
								$data['message'] .= '<br />'.$this->cimailer->ErrorInfo;
							}
						} catch (phpmailerException $e) {
							echo $e->errorMessage(); //Pretty error messages from PHPMailer
							$data['message'] = $this->lang->line('mail_not_send');
						} catch (Exception $e) {
							echo $e->getMessage(); //Boring error messages from anything else!
							$data['message'] = $this->lang->line('mail_not_send');
						}
					}else{
						$this->user_model->delete_user($id);
						$data['message'] = $this->lang->line('company_not_save');
						
					}
				}else{
					$this->load->library('cimailer','cimailer');
					$file = APPPATH.'../assets/mail/user_regis.txt';
					$handle = fopen($file,'r');
					$body = '';
					if ($handle) {
						while (!feof($handle)) {
							$file_ = fgets($handle, 4096);
							$body .= $file_."<br>";
						}
						fclose($handle);
					}
					
					try {
						//$this->cimailer->IsMail();
						$this->cimailer->CharSet="utf-8";
						$this->cimailer->IsHTML(true);
						$this->cimailer->From = $this->config->item('main_email');
						
						$body = str_replace('{NAME}',$_POST['firstname'],$body);
						$body = str_replace('{LASTNAME}',$_POST['lastname'],$body);
						$body = str_replace('{USERNAME}',$member['username'],$body);
						$body = str_replace('{SITENAME}',$this->config->item('site_name'),$body);
						$body = str_replace('{SECCODE}',$member['seckey'],$body);
						$body = str_replace('{PASSWORD}',$_POST['password'],$body);
						$body = str_replace('{CONFIRMLINK}',base_url()."user/register/confirm/{$member['seckey']}",$body);
						
						$this->cimailer->FromName = $this->config->item('register_conf_title');
						$this->cimailer->AddReplyTo($this->config->item('main_email'), $this->config->item('register_conf_title'));
						$this->cimailer->AddAddress($member['email']);
						$this->cimailer->Subject = $this->config->item('register_conf_title');
						$this->cimailer->Body = $body;
						
						if($this->cimailer->Send()){
							$data['message'] = $this->lang->line('regis_complete');
						}else{
							$data['message'] = $this->lang->line('mail_not_send');
							$data['message'] .= '<br />'.$this->cimailer->ErrorInfo;
						}
					} catch (phpmailerException $e) {
						echo $e->errorMessage(); //Pretty error messages from PHPMailer
						$data['message'] = $this->lang->line('mail_not_send');
					} catch (Exception $e) {
						echo $e->getMessage(); //Boring error messages from anything else!
						$data['message'] = $this->lang->line('mail_not_send');
					}
				}
			}else{
				$data['message'] = $this->lang->line('data_not_save');
			}
			
			$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('register_result');
			$data['block_title'] = $this->lang->line('register_result');
			$this->template->set_template('page');
			$this->template->write_view('header','home/master/header',$header , false);
			
			//$banner = $this->banner_model->get_banner();
			$banner['user_block'] = get_user_box();
			$this->template->write_view('sideleft','home/master/sidebar_left',$banner);
			$this->template->write_view('sideright','home/master/sidebar_right',$banner);
			
			$this->template->write_view('search_form','home/master/page_search');
			$this->template->write_view('content', 'home/result_message',$data);
			$this->template->write_view('footer','home/master/footer');
			$this->template->render();
		}
	}
	
	function email_confirm()
	{
		if($this->session->userdata('logged_in') == FALSE){
			$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('email_confirm');
			$this->template->set_template('page');
			$this->template->write_view('header','home/master/header',$header , false);
			$data['block_title'] = $this->lang->line('email_confirm');
			//$banner = $this->banner_model->get_banner();
			$banner['user_block'] = get_user_box();
			$this->template->write_view('sideleft','home/master/sidebar_left',$banner);
			$this->template->write_view('sideright','home/master/sidebar_right',$banner);
			
			$this->template->write_view('search_form','home/master/page_search');
			$this->template->write_view('content', 'email_confirm',$data);
			$this->template->write_view('footer','home/master/footer');
			$this->template->render();
		}else{
			redirect('/user/dashboard');
		}
	}
	
	function email_confirm_send()
	{
		$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('email_confirm');
		
		$user = $_POST['user'];
		$result = $this->user_model->getUserInfo($user);
		if($result){
			$this->load->library('cimailer','cimailer');
			$file = APPPATH.'../assets/mail/user_mailconfirm.txt';
			$handle = fopen($file,'r');
			$body = '';
			if ($handle) {
				while (!feof($handle)) {
					$file_ = fgets($handle, 4096);
					$body .= $file_."<br>";
				}
				fclose($handle);
			}
			
			try{
				//$this->cimailer->IsMail();
				$this->cimailer->CharSet="utf-8";
				$this->cimailer->IsHTML(true);
				$this->cimailer->From = $this->config->item('main_email');
				
				$body = str_replace('{NAME}',$result['firstname'],$body);
				$body = str_replace('{LASTNAME}',$result['lastname'],$body);
				$body = str_replace('{USERNAME}',$result['username'],$body);
				$body = str_replace('{SITENAME}',$this->config->item('site_name'),$body);
				$body = str_replace('{SECCODE}',$result['seckey'],$body);
				$body = str_replace('{CONFIRMLINK}',base_url()."user/register/confirm/{$result['seckey']}",$body);
				
				$this->cimailer->FromName = $this->config->item('register_conf_title');
				$this->cimailer->AddReplyTo($this->config->item('main_email'), $this->config->item('register_conf_title'));
				$this->cimailer->AddAddress($result['email']);
				$this->cimailer->Subject = $this->config->item('register_conf_title');
				$this->cimailer->Body = $body;
				
				if($this->cimailer->Send()){
					$data['message'] = $this->lang->line('mail_confirm_send');
				}else{
					$data['message'] = $this->lang->line('mail_not_send');
					$data['message'] .= '<br />'.$this->cimailer->ErrorInfo;
				}
			} catch (phpmailerException $e) {
				echo $e->errorMessage(); //Pretty error messages from PHPMailer
				$data['message'] = $this->lang->line('mail_not_send');
			} catch (Exception $e) {
				echo $e->getMessage(); //Boring error messages from anything else!
				$data['message'] = $this->lang->line('mail_not_send');
			}
		}else{
			$data['message'] = $this->lang->line('password_wrong');
		}
		
		$this->template->set_template('page');
		$this->template->write_view('header','home/master/header',$header , false);
		$data['block_title'] = $this->lang->line('email_confirm');	
		//$banner = $this->banner_model->get_banner();
		$banner['user_block'] = get_user_box();
		$this->template->write_view('sideleft','home/master/sidebar_left',$banner);
		$this->template->write_view('sideright','home/master/sidebar_right',$banner);
			
		$this->template->write_view('search_form','home/master/page_search');
		$this->template->write_view('content', 'home/result_message',$data);
		$this->template->write_view('footer','home/master/footer');
		$this->template->render();
	}
	
	function register_confirm($sec_code='')
	{
		if($sec_code!=''){
			$user_info = $this->user_model->getUserBySeccode($sec_code);
			if($this->user_model->email_confirm($sec_code)){
				
				$time = time();
				//var_dump($user_info['gold_regis']);
				if($user_info['gold_regis']==1){
					if($this->user_model->regis_gold($user_info['id'],$time)){
						$this->load->library('cimailer','cimailer');
						$file = APPPATH.'../assets/mail/user_gold_regis.txt';
						$handle = fopen($file,'r');
						$body = '';
						if ($handle) {
							while (!feof($handle)) {
								$file_ = fgets($handle, 4096);
								$body .= $file_."<br>";
							}
							fclose($handle);
						}
						
						try{
							//$this->cimailer->IsMail();
							$this->cimailer->CharSet="utf-8";
							$this->cimailer->IsHTML(true);
							$this->cimailer->From = $this->config->item('main_email');
							
							$body = str_replace('{NAME}',$user_info['firstname'],$body);
							$body = str_replace('{LASTNAME}',$user_info['lastname'],$body);
							$body = str_replace('{SITENAME}',$this->config->item('site_name'),$body);
							$body = str_replace('{GOLDURL}','<a href="'.site_url().'gold" title="'.$this->lang->line('gold_register').'">'.$this->lang->line('gold').'</a>',$body);
							$body = str_replace('{EMAIL}',$this->config->item('main_email'),$body);
							$body = str_replace('{PAIDURL}','<a href="'.site_url().'paid-form" title="'.$this->lang->line('paid_form').'">'.$this->lang->line('paid_form').'</a>',$body);
							
							$this->cimailer->FromName = $this->config->item('site_name').' : '.$this->lang->line('gold_register');
							$this->cimailer->AddReplyTo($this->config->item('main_email'), $this->config->item('site_name').' : '.$this->lang->line('gold_register'));
							$this->cimailer->AddAddress($user_info['email']);
							$this->cimailer->Subject = $this->config->item('site_name').' : '.$this->lang->line('gold_register');
							$this->cimailer->Body = $body;
							
							if($this->cimailer->Send()){
								$data['message'] = $this->lang->line('mail_confirm_complete');
								$data['message'] .= $this->lang->line('mail_confirm_complete_gold_message');
							}else{
								$data['message'] = $this->lang->line('mail_not_send');
								$data['message'] .= '<br />'.$this->cimailer->ErrorInfo;
							}
						} catch (phpmailerException $e) {
							echo $e->errorMessage(); //Pretty error messages from PHPMailer
							$data['message'] = $this->lang->line('mail_not_send');
						} catch (Exception $e) {
							echo $e->getMessage(); //Boring error messages from anything else!
							$data['message'] = $this->lang->line('mail_not_send');
						}
					}else{
						$data['message'] = $this->lang->line('mail_confirm_complete');
					}
				}else{
					$data['message'] = $this->lang->line('mail_confirm_complete');
				}
			}else{
				$data['message'] = $this->lang->line('wrong_seccode');
			}
		}else{
			$data['message'] = $this->lang->line('wrong_seccode');
		}
		
		$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('register_confirm');
		$this->template->set_template('page');
		$this->template->write_view('header','home/master/header',$header , false);
		$data['block_title'] = $this->lang->line('register_confirm');	
		//$banner = $this->banner_model->get_banner();
		$banner['user_block'] = get_user_box();
		$this->template->write_view('sideleft','home/master/sidebar_left',$banner);
		$this->template->write_view('sideright','home/master/sidebar_right',$banner);
			
		$this->template->write_view('search_form','home/master/page_search');
		$this->template->write_view('content', 'home/result_message',$data);
		$this->template->write_view('footer','home/master/footer');
		$this->template->render();
	}
	
	function email_existed()
	{
		$email = $_GET['email'];
		$result = $this->user_model->getUserByEmail($email);
		
		if(isset($result['email'])){
			echo 'false';
		}else{
			echo 'true';
		}
	}
	
	function user_existed()
	{
		$username = $_GET['username'];
		$result = $this->user_model->getUserByUsername($username);
		
		if(isset($result['username'])){
			echo 'false';
		}else{
			echo 'true';
		}
	}
	
	function forgotpass()
	{
		if($this->session->userdata('logged_in') == FALSE){
			$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('forget_password');
			$this->template->set_template('page');
			$this->template->write_view('header','home/master/header',$header , false);
			$data['block_title'] = $this->lang->line('forget_password');
			//$banner = $this->banner_model->get_banner();
			$banner['user_block'] = get_user_box();
			$this->template->write_view('sideleft','home/master/sidebar_left',$banner);
			$this->template->write_view('sideright','home/master/sidebar_right',$banner);
			
			$this->template->write_view('search_form','home/master/page_search');
			$this->template->write_view('content', 'forgetpass',$data);
			$this->template->write_view('footer','home/master/footer');
			$this->template->render();
		}else{
			redirect('/user/dashboard');
		}
	}
	
	function forgotpass_send()
	{
		$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('forget_password');
		
		$user = $_POST['user'];
		$result = $this->user_model->getUserInfo($user);
		if($result){
			$this->load->library('cimailer','cimailer');
			$file = APPPATH.'../assets/mail/user_forgotpass.txt';
			$handle = fopen($file,'r');
			$body = '';
			if ($handle) {
				while (!feof($handle)) {
					$file_ = fgets($handle, 4096);
					$body .= $file_."<br>";
				}
				fclose($handle);
			}
			
			try{
				//$this->cimailer->IsMail();
				$this->cimailer->CharSet="utf-8";
				$this->cimailer->IsHTML(true);
				$this->cimailer->From = $this->config->item('main_email');
				
				$body = str_replace('{NAME}',$result['firstname'],$body);
				$body = str_replace('{LASTNAME}',$result['lastname'],$body);
				$body = str_replace('{SITENAME}',$this->config->item('site_name'),$body);
				$body = str_replace('{CONFIRMLINK}',base_url()."user/forgotpass/confirm/{$result['seckey']}+{$result['id']}",$body);
				
				$this->cimailer->FromName = $this->config->item('forgotpass_conf_title');
				$this->cimailer->AddReplyTo($this->config->item('main_email'), $this->config->item('forgotpass_conf_title'));
				$this->cimailer->AddAddress($result['email']);
				$this->cimailer->Subject = $this->config->item('forgotpass_conf_title');
				$this->cimailer->Body = $body;
				
				if($this->cimailer->Send()){
					$data['message'] = $this->lang->line('next_step_mail');
				}else{
					$data['message'] = $this->lang->line('mail_not_send');
					$data['message'] .= '<br />'.$this->cimailer->ErrorInfo;
				}
			} catch (phpmailerException $e) {
				echo $e->errorMessage(); //Pretty error messages from PHPMailer
				$data['message'] = $this->lang->line('mail_not_send');
			} catch (Exception $e) {
				echo $e->getMessage(); //Boring error messages from anything else!
				$data['message'] = $this->lang->line('mail_not_send');
			}
		}else{
			$data['message'] = $this->lang->line('password_wrong');
		}
		
		$this->template->set_template('page');
		$this->template->write_view('header','home/master/header',$header , false);
		$data['block_title'] = $this->lang->line('forget_password');
		//$banner = $this->banner_model->get_banner();
		$banner['user_block'] = get_user_box();
		$this->template->write_view('sideleft','home/master/sidebar_left',$banner);
		$this->template->write_view('sideright','home/master/sidebar_right',$banner);
			
		$this->template->write_view('search_form','home/master/page_search');
		$this->template->write_view('content', 'home/result_message',$data);
		$this->template->write_view('footer','home/master/footer');
		$this->template->render();
	}
	
	function forgotpass_confirm($sec_code='')
	{
		if($sec_code!=''){
			$code = explode('+',$sec_code);
			$user['seckey'] = $code[0];
			$user['id'] = $code[1];
			$user['password'] = substr(md5($code[0].$code[1]),0,7);
			if($this->user_model->update_user_forgotpass($user)){
				
				$result = $this->user_model->getUserInfoByID($user['id']);
				
				$this->load->library('cimailer','cimailer');
				$file = APPPATH.'../assets/mail/user_newpass.txt';
				$handle = fopen($file,'r');
				$body = '';
				if ($handle) {
					while (!feof($handle)) {
						$file_ = fgets($handle, 4096);
						$body .= $file_."<br>";
					}
					fclose($handle);
				}
				
				try{
					//$this->cimailer->IsMail();
					$this->cimailer->CharSet="utf-8";
					$this->cimailer->IsHTML(true);
					$this->cimailer->From = $this->config->item('main_email');
					
					$body = str_replace('{NAME}',$result['firstname'],$body);
					$body = str_replace('{LASTNAME}',$result['lastname'],$body);
					$body = str_replace('{SITENAME}',$this->config->item('site_name'),$body);
					$body = str_replace('{PASSWORD}',$user['password'],$body);
					
					$this->cimailer->FromName = $this->config->item('newpass_title');
					$this->cimailer->AddReplyTo($this->config->item('main_email'), $this->config->item('newpass_title'));
					$this->cimailer->AddAddress($result['email']);
					$this->cimailer->Subject = $this->config->item('newpass_title');
					$this->cimailer->Body = $body;
					
					if($this->cimailer->Send()){
						$data['message'] = $this->lang->line('new_password_send');
					}else{
						$data['message'] = $this->lang->line('mail_not_send');
						$data['message'] .= '<br />'.$this->cimailer->ErrorInfo;
					}
				} catch (phpmailerException $e) {
					echo $e->errorMessage(); //Pretty error messages from PHPMailer
					$data['message'] = $this->lang->line('mail_not_send');
				} catch (Exception $e) {
					echo $e->getMessage(); //Boring error messages from anything else!
					$data['message'] = $this->lang->line('mail_not_send');
				}
			}else{
				$data['message'] = $this->lang->line('wrong_seccode');
			}
		}else{
			$data['message'] = $this->lang->line('wrong_seccode');
		}
		
		$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('forget_password');
		$this->template->set_template('page');
		$this->template->write_view('header','home/master/header',$header , false);
		$data['block_title'] = $this->lang->line('forget_password');
		//$banner = $this->banner_model->get_banner();
		$banner['user_block'] = get_user_box();
		$this->template->write_view('sideleft','home/master/sidebar_left',$banner);
		$this->template->write_view('sideright','home/master/sidebar_right',$banner);
			
		$this->template->write_view('search_form','home/master/page_search');
		$this->template->write_view('content', 'home/result_message',$data);
		$this->template->write_view('footer','home/master/footer');
		$this->template->render();
	}
	
	function login_auth()
	{
		if(isset($_POST['username']) AND $this->session->userdata('logged_in') == FALSE){
			$user['username'] = $_POST['username'];
			$password = $_POST['password'];
			
			$user_info = $this->user_model->getUserInfo($_POST['username']);
			
			if($user_info AND md5($password) == $user_info['password']){
				if($user_info['confirm']==1){
					$newdata = array(
						'username'  => $user['username'],
						'user_id'  => $user_info['id'],
						'role_id'   => $user_info['role_id'],
						'email'   => $user_info['email'],
						'logged_in' => TRUE
					);
					$this->session->set_userdata($newdata);
					
					
					$data['message'] = $this->lang->line('login_complete');
					//$data['redirect_url'] = (getenv("HTTP_REFERER"));
					$data['redirect_url'] = site_url().'user/dashboard';
				}else{
					$data['redirect_url'] = site_url().'user/login';
					$data['message'] = $this->lang->line('unconfirm');
				}
				
			}else{
				$data['redirect_url'] = site_url().'user/login';
				$data['message'] = $this->lang->line('password_wrong');
			}
			
			//$header['title'] = 'Login Result';
			//$this->template->set_template('page');
			//$this->template->write_view('header','home/master/header',$header , false);
			//$this->template->write_view('sideleft','home/master/sidebar_left');
			//$this->template->write_view('sideright','home/master/sidebar_right');
			//$this->template->write_view('search_form','home/master/page_search');
			$this->template->write_view('content', 'login_auth',$data);
			//$this->template->write_view('footer','home/master/footer');
			$this->template->render();
		}else{
			redirect(site_url());
		}
	}
	
	function update()
	{
		//echo '<pre>';
		//var_dump($_POST);
		//echo '</pre>';
		//exit;
		
		if(!isset($_POST['email']) OR $_POST['email']==''){
			redirect(site_url().'user/dashboard');
		}else{
			$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('update_user_info');
			$time = time();
			
			
			$id = $_POST['user_id'];
			$member['id'] = $id;
			$member['role_id'] = $_POST['group'];
			$member['firstname'] = $_POST['firstname'];
			$member['lastname'] = $_POST['lastname'];
			$member['cpassword'] = md5($_POST['cpassword']);
			$member['password'] = trim($_POST['password']);
			$member['tel'] = $_POST['member_tel'];
			$member['modified'] = $time;
			$member['seckey'] = md5($time.rand(-100,100));
			
			if($this->user_model->update_supplier($member)){
				if($_POST['group']==2){
					$this->load->model('admin/province_model','province_model');
					$company_id = $_POST['company_id'];
					$company['id'] = $company_id;
					$company['name'] = $_POST['company_name'];
					$company['main_cat_id'] = $_POST['company_category'];
					$company['cat_id'] = $_POST['company_subcat'];
					$company['address'] = $_POST['company_address'];
					$company['district'] = $_POST['company_district'];
					$company['geo_id'] = $this->province_model->get_geo_id($_POST['company_province']);
					$company['province'] = $_POST['company_province'];
					$company['postcode'] = $_POST['company_postcode'];
					$company['country'] = $_POST['company_country'];
					$company['agent'] = $_POST['company_agent'];
					$company['website'] = $_POST['company_website'];
					$company['email'] = $_POST['company_email'];
					$company['tel'] = $_POST['company_tel'];
					$company['fax'] = $_POST['company_fax'];
					$company['brand'] = $_POST['company_brand'];
					$company['c_modified'] = $time;
					
					if($this->user_model->update_company($company)){
						$this->load->library('ciupload');
						$img_msg = '';
						$logo_msg = '';
						if(isset($_FILES["img"]) && is_uploaded_file($_FILES["img"]["tmp_name"]) && $_FILES["img"]["tmp_name"]!=''){
							$this->ciupload->Upload($_FILES['img']);
							if ($this->ciupload->uploaded){
								$this->ciupload->image_resize = true;
								$this->ciupload->image_ratio_fill = true;
								$this->ciupload->image_x = 156;
								$this->ciupload->image_y = 100;
								$this->ciupload->Process(APPPATH.'../assets/image/company/'.$company_id);
								
								if ($this->ciupload->processed){
									$input['user_id'] = $id;
									$input['id'] = $company_id;
									$input['img'] = $this->ciupload->file_dst_name;
									$result = $this->user_model->update_company_img($input);
									if($result==0){
										@unlink(APPPATH.'../assets/image/company/'.$company_id.'/'.$this->ciupload->file_dst_name);
										$img_msg = $this->lang->line('image_not_upload');
									}else{
										@unlink(APPPATH.'../assets/image/company/'.$company_id.'/'.$_POST['old_img']);
									}
								}else{
									$img_msg = $this->lang->line('image_not_upload');
								}
							}else{
								$img_msg = $this->lang->line('image_not_upload');
							}
						}
						
						if(isset($_FILES["logoimg"]) && is_uploaded_file($_FILES["logoimg"]["tmp_name"]) && $_FILES["logoimg"]["tmp_name"]!=''){
							$this->ciupload->Upload($_FILES['logoimg']);
							if ($this->ciupload->uploaded){
								$this->ciupload->image_resize = true;
								$this->ciupload->image_ratio_fill = true;
								$this->ciupload->image_x = 35;
								$this->ciupload->image_y = 35;
								$this->ciupload->Process(APPPATH.'../assets/image/company/'.$company_id);
								
								if ($this->ciupload->processed){
									$input['user_id'] = $id;
									$input['id'] = $company_id;
									$input['logo'] = $this->ciupload->file_dst_name;
									$result = $this->user_model->update_company_logo($input);
									if($result==0){
										@unlink(APPPATH.'../assets/image/company/'.$company_id.'/'.$this->ciupload->file_dst_name);
										$logo_msg = $this->lang->line('image_not_upload');
									}else{
										@unlink(APPPATH.'../assets/image/company/'.$company_id.'/'.$_POST['old_logo']);
									}
								}else{
									$logo_msg = $this->lang->line('image_not_upload');
								}
							}else{
								$logo_msg = $this->lang->line('image_not_upload');
							}
						}
						
						$data['message'] = $this->lang->line('user_info_save');
					}else{
						//$this->user_model->delete_user($id);
						$data['message'] = $this->lang->line('company_not_save');
						
					}
				}else{
					$this->load->library('cimailer','cimailer');
					$file = APPPATH.'../assets/mail/user_regis.txt';
					$handle = fopen($file,'r');
					$body = '';
					if ($handle) {
						while (!feof($handle)) {
							$file_ = fgets($handle, 4096);
							$body .= $file_."<br>";
						}
						fclose($handle);
					}
					
					try{
						//$this->cimailer->IsMail();
						$this->cimailer->CharSet="utf-8";
						$this->cimailer->IsHTML(true);
						$this->cimailer->From = $this->config->item('main_email');
						
						$body = str_replace('{NAME}',$_POST['firstname'],$body);
						$body = str_replace('{LASTNAME}',$_POST['lastname'],$body);
						$body = str_replace('{USERNAME}',$member['username'],$body);
						$body = str_replace('{SITENAME}',$this->config->item('site_name'),$body);
						$body = str_replace('{SECCODE}',$member['seckey'],$body);
						$body = str_replace('{PASSWORD}',$_POST['password'],$body);
						$body = str_replace('{CONFIRMLINK}',base_url()."user/register/confirm/{$member['seckey']}",$body);
						
						$this->cimailer->FromName = $this->config->item('register_conf_title');
						$this->cimailer->AddReplyTo($this->config->item('main_email'), $this->config->item('register_conf_title'));
						$this->cimailer->AddAddress($member['email']);
						$this->cimailer->Subject = $this->config->item('register_conf_title');
						$this->cimailer->Body = $body;
						
						if($this->cimailer->Send()){
							$data['message'] = $this->lang->line('regis_complete');
						}else{
							$data['message'] = $this->lang->line('mail_not_send');
							$data['message'] .= '<br />'.$this->cimailer->ErrorInfo;
						}
					} catch (phpmailerException $e) {
						echo $e->errorMessage(); //Pretty error messages from PHPMailer
						$data['message'] = $this->lang->line('mail_not_send');
					} catch (Exception $e) {
						echo $e->getMessage(); //Boring error messages from anything else!
						$data['message'] = $this->lang->line('mail_not_send');
					}
				}
			}else{
				$data['message'] = $this->lang->line('data_not_save');
			}
			
			$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('update_user_info');
			$data['block_title'] = $this->lang->line('update_user_info');
			$this->template->set_template('page');
			$this->template->write_view('header','home/master/header',$header , false);
			
			//$banner = $this->banner_model->get_banner();
			$banner['user_block'] = get_user_box();
			$this->template->write_view('sideleft','home/master/sidebar_left',$banner);
			$this->template->write_view('sideright','home/master/sidebar_right',$banner);
			
			$this->template->write_view('search_form','home/master/page_search');
			$this->template->write_view('content', 'home/result_message',$data);
			$this->template->write_view('footer','home/master/footer');
			$this->template->render();
			redirect(base_url().'/user/dashboard');
		}
	}
	
	function check_pass(){
		$password = md5(trim($_GET['cpassword']));
		$result = $this->user_model->getUserByUsername($this->session->userdata('username'));
		
		if(isset($result['username'])){
			if($password==$result['password']){
				echo 'true';
			}else{
				echo 'false';
			}
		}else{
			echo 'false';
		}
	}
	
	function build_website()
	{
		if($this->session->userdata('logged_in') === FALSE){
			redirect(base_url().'/user/login');
		}else{
			$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('build_website');
			$this->template->set_template('page');
			$this->template->write_view('header','home/master/header',$header , false);
			
			//$banner = $this->banner_model->get_banner();
			$banner['user_block'] = get_user_box();
			$this->template->write_view('sideleft','home/master/sidebar_left',$banner);
			$this->template->write_view('sideright','home/master/sidebar_right',$banner);
			
			$this->template->write_view('search_form','home/master/page_search');
			
			$data['block_title'] = $this->lang->line('build_website');
			
			$company_info = $this->user_model->getCompanyInfo($this->session->userdata('user_id'));
			$website_info = $this->user_model->getCompanyWebsiteByCompanyId($company_info['id']);
			
			if(count($website_info) > 0){
				$website_info['created'] = TRUE;
				
				$website_info['status_0'] = '';
				$website_info['status_1'] = '';
				switch($website_info['status']){
					case 0 :
						$website_info['status_0'] = 'checked="checked"';
						break;
					case 1 :
						$website_info['status_1'] = 'checked="checked"';
						break;
					default :
						$website_info['status_0'] = 'checked="checked"';
				}
			}else{
				$website_info['id'] = '';
				$website_info['company_id'] = $company_info['id'];
				$website_info['title'] = $company_info['name'];
				$website_info['description'] = '';
				$website_info['body_bg_color'] = '#cdcdcd';
				$website_info['img'] = '';
				$website_info['detail'] = '';
				$website_info['status_0'] = 'checked="checked"';
				$website_info['status_1'] = '';
				$website_info['created'] = FALSE;
			}
			
			$data['website_info'] = $website_info;
			$this->template->write_view('content', 'build_website' , $data);
			
			$this->template->write_view('footer','home/master/footer');
			$this->template->render();
		}
	}
	
	function build_website_save()
	{
		if(!isset($_POST['company_id']) OR $_POST['company_id']==''){
			redirect(site_url().'user/website');
		}else{
			$id = trim($_POST['id']);
			$input['company_id'] = $_POST['company_id'];
			$input['title'] = $_POST['title'];
			$input['description'] = $_POST['description'];
			$input['body_bg_color'] = trim($_POST['body_bg_color']);
			$input['detail'] = trim($_POST['detail']);
			$input['status'] = $_POST['status'];
			$input['member_id'] = $this->session->userdata('user_id');
			
			if($id==''){
				$input['add_date'] = time();
				$check = $this->user_model->save_website($input);
				$id = $check;
			}else{
				$input['update_date'] = time();
				$check = $this->user_model->update_website($input , $id);
			}
			
			if($check){
				
				if($_POST['status']==1){
					$input = array();
					$input['website'] = base_url().'site/'.$id.'/'.urlencode($_POST['title']);
					$this->user_model->update_company2($input,$_POST['company_id']);
				}
				
				$this->load->library('ciupload');
				$img_msg = '';
				if(isset($_FILES["img"]) && is_uploaded_file($_FILES["img"]["tmp_name"]) && $_FILES["img"]["tmp_name"]!=''){
					$this->ciupload->Upload($_FILES['img']);
					if ($this->ciupload->uploaded){
						$this->ciupload->image_resize = true;
						$this->ciupload->image_ratio_fill = true;
						$this->ciupload->image_x = 730;
						$this->ciupload->image_y = 200;
						$this->ciupload->Process(APPPATH.'../assets/image/website/'.$id);
						
						if ($this->ciupload->processed){
							$input['img'] = $this->ciupload->file_dst_name;
							$result = $this->user_model->update_website($input , $id);
							if($result==0){
								@unlink(APPPATH.'../assets/image/website/'.$id.'/'.$this->ciupload->file_dst_name);
								$img_msg = $this->lang->line('image_not_upload');
							}else{
								$data['message'] = $this->lang->line('website_save');
								if(trim($_POST['id'])!='' AND trim($_POST['old_img'])!=''){
								@unlink(APPPATH.'../assets/image/website/'.$id.'/'.$_POST['old_img']);
								}
							}
						}else{
							$img_msg = $this->lang->line('image_not_upload');
						}
					}else{
						$img_msg = $this->lang->line('image_not_upload');
					}
				}else{
					$data['message'] = $this->lang->line('website_save');
				}
			}else{
				$data['message'] = $this->lang->line('data_not_save');
			}
			
			$header['title'] = $this->config->item('site_name').' : '.$this->lang->line('build_website');
			$data['block_title'] = $this->lang->line('build_website');
			$this->template->set_template('page');
			$this->template->write_view('header','home/master/header',$header , false);
			
			//$banner = $this->banner_model->get_banner();
			$banner['user_block'] = get_user_box();
			$this->template->write_view('sideleft','home/master/sidebar_left',$banner);
			$this->template->write_view('sideright','home/master/sidebar_right',$banner);
			
			$this->template->write_view('search_form','home/master/page_search');
			$this->template->write_view('content', 'home/result_message',$data);
			$this->template->write_view('footer','home/master/footer');
			$this->template->render();
			redirect(base_url().'/user/website');
		}
	}
	
	function user_website($id)
	{
		$this->template->set_template('website');
		
		$website_info = $this->user_model->getCompanyWebsite($id);
		
		if(count($website_info) > 0 AND $website_info['status']!=0 AND $website_info['active']!=0 OR $website_info['member_id']==$this->session->userdata('user_id')){
			$this->template->write('title', $website_info['title'].' Power by govermentbestbuy.com' , TRUE);
			$this->template->write('description', $website_info['description'] , TRUE);
			$this->template->write('keywords', $website_info['title'] , TRUE);
			$this->template->write('companyname', $website_info['title'] , TRUE);
			$this->template->write('content', $website_info['detail'] , TRUE);
			$this->template->write('body_bg', $website_info['body_bg_color'] , TRUE);
			
			if(trim($website_info['img'])!=''){
				$this->template->write('banner', "assets/image/website/{$website_info['id']}/{$website_info['img']}" , TRUE);
			}
		}
		
		$this->template->render();
	}
}

/* End of file user.php */
/* Location: ./application/modules/user/controllers/user.php */